//
//  BViewController.m
//  nstimer循环引用
//
//  Created by keisun on 2018/10/31.
//  Copyright © 2018年 keisun. All rights reserved.
//

#import "BViewController.h"
#import "WeakProxy.h"
#import "YYWeakProxy.h"
#import "NSTimer+Extension.h"
#import "YYTimer.h"
#import "CGTimerTempTarget.h"

@interface BViewController ()
//timer用weak也无法避免循环引用，因为target释放依赖timer，而timer的释放操作在target的dealloc方法中
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSMutableArray *marr;
@end

@implementation BViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //NSTimer和CADisplayLink 都会引起循环引用，解决方式看这个https://www.jianshu.com/p/45481ac0b5d5
    
    //方法一：链接中作者构思出来用block解决（控制器dealloc时必须搭配invalidate，否则控制器纵然会销毁但定时器还会继续运行）
        //引入数组只为了说明block里面必须要弱引用，否则也会造成循环引用
    self.marr = [NSMutableArray array];
    __weak typeof(self) weakSelf = self;
    NSTimer *timer = [NSTimer hr_scheduledTimerWithTimeInterval:1 block:^{
        NSLog(@"block中走呀走");
        [weakSelf.marr removeAllObjects];
        [weakSelf.marr addObject:@"1"];
        NSLog(@"%@",weakSelf.marr);
    } repeats:YES];
    self.timer = timer;
    
    //方法二：YYKit自己造的轮子（用到了GCD原理），手写计时器，很厉害（该timer指针要强引用），控制器dealloc时可以不用invalidate（建议用，更有保障性）
//    YYTimer *timer = [YYTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) repeats:YES];
//    [timer fire];
//    self.timer = timer;
    
    //方法三（最好）控制器dealloc时可以不用invalidate（建议用，更有保障性）
    //YYWeakProxy其实是YYKit避免timer循环引用的解决方案，很好用，没有侵入性，替换target即可
//    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[YYWeakProxy proxyWithTarget:self]  selector:@selector(timerAction) userInfo:nil repeats:YES];
//    self.timer = timer;
    
    //2019.3.19 方法四：https://www.jianshu.com/p/aaf7b13864d9
    //控制器dealloc时可以不用invalidate（建议用，更有保障性）
//    [CGTimerTempTarget scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 40, 50, 50)];
    [btn setTitle:@"b返回" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor greenColor];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:btn];
}

-(void)timerAction{
    NSLog(@"定时器走呀走");
}

-(void)btnClick{
//    [self dismissViewControllerAnimated:YES completion:nil];
    //或者 想回到哪个页面，就由哪个页面dismissViewController (详见https://www.cnblogs.com/acBool/p/5994663.html)
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

-(void)dealloc{
    [self.timer invalidate];
    NSLog(@"BViewController销毁了");
}

@end
